package com.jxc.action.spgl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.Json;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VUser;
import com.jxc.service.GoodsServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.ExceptionUtil;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ModelDriven;

@Namespace("/spgl")
@Action(value = "goodsAction", results = { @Result(name = "goods", location = "/goods/goods.jsp"),
		@Result(name = "goodsAdd", location = "/goods/goodsAdd.jsp"), @Result(name = "goodsEdit", location = "/goods/goodsEdit.jsp"),
		@Result(name = "unsalableGoods", location = "/goods/unsalableGoods.jsp") })
public class GoodsAction extends BaseAction implements ModelDriven<VGoods> {
	private final static Logger logger = Logger.getLogger(GoodsAction.class);

	private VGoods model = new VGoods();

	@Autowired
	private GoodsServiceI goodsService;
	@Autowired
	private UserServiceI userService;
	@Autowired
	private RepertoryServiceI repertoryService;

	public String goods() {
		getSubAuths("SPGL_SPGL");
		return "goods";
	}

	public String goodsAdd() {
		return "goodsAdd";
	}

	public String goodsEdit() {
		return "goodsEdit";
	}

	public String unsalableGoods() {
		return "unsalableGoods";
	}

	public void unsaleDatagrid() {
		if (model.getRid() != null) {
			this.writeJson(goodsService.unsaleDatagrid(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(goodsService.unsaleDatagrid(model));
			} else {
				VRepertory vrepertory = new VRepertory();
				vrepertory.setUid(sessionInfo.getUserId());
				List<VRepertory> vrepertories = repertoryService.list(vrepertory);
				if (vrepertories != null && vrepertories.size() > 0) {
					List<VGoods> rows = new ArrayList<VGoods>();
					Long total = 0l;
					for (VRepertory vre : vrepertories) {
						model.setRid(vre.getId());
						DataGrid subDg = goodsService.unsaleDatagrid(model);
						rows.addAll(subDg.getRows());
						total += subDg.getTotal();
					}
					DataGrid totalDg = new DataGrid();
					totalDg.setRows(rows);
					totalDg.setTotal(total);
					this.writeJson(totalDg);
				} else {
					DataGrid dg = new DataGrid();
					dg.setTotal(0l);
					dg.setRows(new ArrayList<VGoods>());
					this.writeJson(dg);
				}
			}
		}
	}

	public void datagrid() {
		// 查询当前用户所属仓库，将仓库添加到查询条件中
		// 如当前用户没有所属仓库，则查询经销商为当前用户的仓库，将所有仓库中的品牌查询出来
		// 如当前用户没有所属仓库，也没有哪个仓库的经销商为当前用户，则返回为空！
		if (model.getRid() != null) {
			this.writeJson(goodsService.datagrid(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(goodsService.datagrid(model));
			} else {
				VRepertory vrepertory = new VRepertory();
				vrepertory.setUid(sessionInfo.getUserId());
				List<VRepertory> vrepertories = repertoryService.list(vrepertory);
				if (vrepertories != null && vrepertories.size() > 0) {
					List<VGoods> rows = new ArrayList<VGoods>();
					Long total = 0l;
					for (VRepertory vre : vrepertories) {
						model.setRid(vre.getId());
						DataGrid subDg = goodsService.datagrid(model);
						rows.addAll(subDg.getRows());
						total += subDg.getTotal();
					}
					DataGrid totalDg = new DataGrid();
					totalDg.setRows(rows);
					totalDg.setTotal(total);
					this.writeJson(totalDg);
				} else {
					DataGrid dg = new DataGrid();
					dg.setTotal(0l);
					dg.setRows(new ArrayList<VGoods>());
					this.writeJson(dg);
				}
			}
		}
	}

	public void noAuth_noPageDatagrid() {
		if (StringUtils.isBlank(model.getBarcode()) && StringUtils.isBlank(model.getType())) {
			this.writeJson(new ArrayList<VGoods>());
		} else
			this.writeJson(goodsService.combobox(model));
	}

	/**
	 * 添加品牌
	 * 
	 */
	public void add() {
		Json j = new Json();
		try {
			VGoods param = new VGoods();
			param.setBarcode(model.getBarcode());
			param.setRid(model.getRid());
			List<VGoods> vgs = goodsService.combobox(param);
			if (vgs.size() > 0) {
				throw new Exception();
			}
			model.setAmount(0);
			model.setInitAmount(0);
			model.setOrderTotal(0);
			model.setOrderReturnTotal(0);
			model.setSaleTotal(0);
			model.setSaleReturnTotal(0);
			model.setDamageTotal(0);
			model.setTransferTotal(0);
			model.setRepertoryTotal(0);
			model.setIsDelete(false);
			model.setLastedSaleTime(new Date());

			goodsService.save(model);
			j.setMsg("添加成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("添加失败，商品已存在！");
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
		super.writeJson(j);
	}

	/**
	 * 修改品牌
	 * 
	 */
	public void edit() {
		Json j = new Json();
		try {
			VGoods param = new VGoods();
			param.setBarcode(model.getBarcode());
			param.setRid(model.getRid());
			List<VGoods> vgs = goodsService.combobox(param);
			if (vgs.size() > 0) {
				for (VGoods vg : vgs) {
					if (vg.getId().longValue() != model.getId().longValue()) {
						throw new Exception();
					}
				}
			}

			goodsService.update(model);
			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (Exception e) {
			logger.error(ExceptionUtil.getExceptionMessage(e));
			j.setMsg("编辑失败，商品已存在！");
		}
		super.writeJson(j);
	}

	/**
	 * 删除品牌
	 * 
	 */
	public void delete() {
		Json j = new Json();
		goodsService.delete(model.getIds());
		j.setSuccess(true);
		j.setMsg("删除成功!");
		super.writeJson(j);
	}

	public void modify() {
		Json j = new Json();
		goodsService.updateLastSaleDate(model.getIds());
		j.setSuccess(true);
		j.setMsg("更新成功!");
		super.writeJson(j);
	}

	public void noAuth_search() {
		Json json = new Json();
		List<VGoods> list = goodsService.search(model);
		if (list != null && list.size() > 0) {
			writeJson(list.get(0));
		} else {
			json.setSuccess(false);
			json.setMsg("没有商品!");
			writeJson(json);
		}
	}

	@Override
	public VGoods getModel() {
		return model;
	}

}
